var redis = require("redis");
var client = redis.createClient(6379, '127.0.0.1');
var logger = require('./logger');

const KEY_TOKEN = `wx_token_key`;
const CHANNEL = `channel-wx-token-updated`;

class RedisToken {

    save(token) {
        return new Promise((resolve, reject) => {
            client.set(KEY_TOKEN, JSON.stringify(token), (err, res) => {
                if (err) {
                    logger.error(`[RedisToken] 保存微信token报错: ${err}`);
                    reject(err);
                } else {
                    logger.debug(`[RedisToken] 保存微信token成功: ${res}`);
                    client.publish(CHANNEL, JSON.stringify(token));
                    logger.debug(`[RedisToken] 发布微信token更新事件通知`);
                    resolve();
                }
            });
        });
    }
}

module.exports = new RedisToken(); // 导出单例实现

// var sub = redis.createClient();
// sub.on("message", (channel, message) => {
//     logger.debug("sub channel " + channel + ": " + message);
// });
// sub.subscribe(CHANNEL);

// new RedisToken().save({ k: 1 });
